package com.example.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


/**
 * mysql02 01 数据源 配置
 */
@Configuration
@MapperScan(basePackages = "com.example.dao.mysql02.**", sqlSessionTemplateRef = "mysqlSqlSessionTemplate02")
public class Mysql02DatasourceConfig {

    @Bean(name = "mysqlDataSource02")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "mysqlSqlSessionFactory02")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqlDataSource02") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        //设置数据源
        bean.setDataSource(dataSource);
        //设置mybatis映射路径
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-mappers/mysql02/**/**.xml"));
        return bean.getObject();
    }

    @Bean(name = "mysqlSqlSessionTemplate02")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory02") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * 配置事务管理，如果使用到事务需要注入该 Bean，否则事务不会生效
     * 在需要的地方加上 @Transactional 注解即可
     */
    @Bean(name = "mysqlDataSourceTransactionManager02")
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("mysqlDataSource01") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


}
